package com.meitianhui.convenitenbuy.module.store.presenter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseMapResponse;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.home.model.bean.BannerBean;
import com.meitianhui.convenitenbuy.module.order.model.bean.EmptyInfo;
import com.meitianhui.convenitenbuy.module.store.contract.StoreDetailContract;
import com.meitianhui.convenitenbuy.module.store.http.StoreApiDataSource;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarEvent;
import com.meitianhui.convenitenbuy.module.store.model.StoreDetailCount;
import com.meitianhui.convenitenbuy.module.store.model.StoreDetailInfo;
import com.meitianhui.convenitenbuy.module.store.model.StoreSelectedGood;
import com.meitianhui.convenitenbuy.module.store.model.StoreType;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreDetailActivity;
import com.meitianhui.convenitenbuy.util.AddToCartUtil;
import com.meitianhui.convenitenbuy.util.GsonParserUtils;
import com.meitianhui.convenitenbuy.util.PixelUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.CustomTipDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by Administrator on 2017/11/2.
 */

public class StoreDetailPresenter implements StoreDetailContract.Presenter {

    private StoreDetailActivity mContext;
    private final StoreDetailContract.View mView;
    private CustomTipDialog mDialog;
    int mStart = 0;
    private boolean mPaySuccess = false;

    public StoreDetailPresenter(StoreDetailContract.View view,
                                StoreDetailActivity context) {
        this.mView = view;
        this.mContext = context;

        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean eventBean) throws Exception {
                if (eventBean.getType() == Constants.EVENT_TYPE_REFRESH) {
                    mPaySuccess = true;
                }
            }
        });
        mContext.mCompositeDisposable.add(subscribe);
    }

    @Override
    public void getStoreDetailInfo(String storeId) {
        String service = "member.storeDetailFind";
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("stores_id", storeId);
        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        if (userToken != null && InfoProvider.getLoginStatus(App.getInstance())) {
            hashMap.put("consumer_id", userToken.getMember_id());
            service = "member.storeDetailForConsumerFind";
        }
        String paramJson = new Gson().toJson(hashMap);

        StoreApiDataSource.getInstance()
                .getStoreDetailInfo(InfoProvider.getAppToken(App.getInstance()), service, paramJson)
                .subscribe(new ResponseObserver<BaseResponse<StoreDetailInfo>>(mContext) {
                    @Override
                    public void onSuccess(BaseResponse<StoreDetailInfo> response) {
                        if (response.data != null) {
                            mView.setBanner(getBanner(response.data));
                            mView.getStoreDetailInfoSuccess(response.data);
                            String service = response.data.detail.getActivity_servcie();
                            mView.setService(getService(service), response.data.detail.getDesc1());
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getStoreSelectedType(String storeId) {
        Map<String, String> map = new HashMap<>();
        map.put("store_id", storeId);
        String paramJson = new Gson().toJson(map);

        StoreApiDataSource.getInstance()
                .getStoreSelectedType(InfoProvider.getAppToken(App.getInstance()),
                        "goods.itemStoreGroupTypeForConsumerFind", paramJson)
                .subscribe(new ResponseObserver<BaseMapResponse>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseMapResponse response) {
                        mView.getStoreSelectTypeSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getStoreSelectedGood(String storeId, String categoryId) {
        String service;
        Map<String, String> map = new HashMap<>();
        map.put("store_id", storeId);
        if (categoryId.equals("推荐")) {
            service = "goods.recommendItemStoreForConsumerListPageFind";
        } else {
            if (!"全部".equals(categoryId)) {
                map.put("category_id", categoryId);
            }
            service = "goods.itemStorePageFindForConsumer";
        }
        String paramJson = new Gson().toJson(map);

        StoreApiDataSource.getInstance()
                .getStoreSelectedGood(InfoProvider.getAppToken(App.getInstance()),
                        service, paramJson)
                .subscribe(new ResponseObserver<BaseResponse<StoreSelectedGood>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<StoreSelectedGood> response) {
                        mView.getStoreSelectedGoodSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getStoreDetailCount(String storeId) {
        Map<String, String> map = new HashMap<>();
        map.put("stores_id", storeId);
        String paramJson = new Gson().toJson(map);

        StoreApiDataSource.getInstance()
                .getStoreDetailCount(InfoProvider.getAppToken(App.getInstance()),
                        "goods.storesActivityCount", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<StoreDetailCount>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<StoreDetailCount> response) {
                        mView.getStoreDetailCountSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void operationCollect(String orderId, String service) {
        Map<String, String> map = new HashMap<>();
        map.put("stores_id", orderId);
        map.put("consumer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        String paramJson = new Gson().toJson(map);

        StoreApiDataSource.getInstance()
                .operationCollect(InfoProvider.getAppToken(App.getInstance()), service, paramJson)
                .subscribe(new ResponseObserver<BaseResponse<EmptyInfo>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<EmptyInfo> response) {
                        mView.operationCollectSuccess(service);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getHyphenateInfo(String storeId) {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", storeId);
        map.put("member_type_key", "stores");
        String paramJson = new Gson().toJson(map);

        StoreApiDataSource.getInstance()
                .getHyphenateInfo(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "chat.getIMUserAccount", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<HyphenateInfo>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<HyphenateInfo> response) {
                        mView.getHyphenateInfoSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.onFail(code, msg);
                    }
                });
    }

    @Override
    public void registerEvent() {
        Disposable disposable = RxBus.get().toFlowable(ShopCarEvent.class).subscribe(new Consumer<ShopCarEvent>() {
            @Override
            public void accept(ShopCarEvent addShopCarEvent) throws Exception {
                if (addShopCarEvent.type == Constants.EVENT_TYPE_CAR_ADD) {   //添加的时候
                    if (mStart == 0) {
                        mStart = PixelUtils.dip2px(11);
                    }
                    /* 起点 */
                    int[] startXY = new int[2];
                    int fx = addShopCarEvent.xy0 + mStart;
                    int fy = addShopCarEvent.xy1 + mStart;
                    startXY[0] = fx;
                    startXY[1] = fy;
                    final ImageView animImg = new ImageView(mContext);
                    animImg.setImageResource(R.drawable.icon_red_bg);
                    ViewGroup anim_mask_layout = AddToCartUtil.createAnimLayout(mContext);
                    anim_mask_layout.addView(animImg);
                    final View v = AddToCartUtil.addViewToAnimLayout(mContext, anim_mask_layout, animImg, startXY, true);
                    if (v == null) {
                        return;
                    }
                    /* 终点 */
                    final View cartView = mContext.findViewById(R.id.txt_card_num_bg);
                    int[] endXY = new int[2];
                    cartView.getLocationInWindow(endXY);
                    int tx = endXY[0];
                    int ty = endXY[1];
                    /* 终点 */
                    int mx = (tx + fx) / 2;
                    int my = (ty + fy) / 2 - 100;
                    AddToCartUtil.startAnimation(v, 0, 0, fx, fy, mx, my, tx, ty, new AddToCartUtil.AnimationListener() {
                        @Override
                        public void onAnimationEnd() {
                            // 动画结束
                            if (addShopCarEvent.number != 0) {
                                mView.getEventData(0, addShopCarEvent.number, addShopCarEvent.shopCarGoodsList);
                            }
                        }
                    });
                } else if (addShopCarEvent.type == Constants.EVENT_TYPE_CAR_RETURN) {
                    if (!mPaySuccess) {
                        mView.getEventData(1, addShopCarEvent.number, addShopCarEvent.shopCarGoodsList);
                    } else {
                        mView.getEventData(1, addShopCarEvent.number, addShopCarEvent.shopCarGoodsList);
                    }
                }

            }
        });
        mContext.mCompositeDisposable.add(disposable);
    }

    @Override
    public void callPhone(String phone) {
        RxPermissions rxPermissions = new RxPermissions(mContext);
        mDialog = new CustomTipDialog(mContext, new CustomTipDialog.DialogClick() {
            @Override
            public void cancelClick() {
                mDialog.stopProgressDialog();
            }

            @Override
            public void submitClick() {
                rxPermissions.requestEach(Manifest.permission.CALL_PHONE).subscribe(permission -> {
                    if (permission.granted) {
                        Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));//拨打电话
                        if (ActivityCompat.checkSelfPermission(mContext,
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        mContext.startActivity(phoneIntent);
                        mDialog.stopProgressDialog();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        TipUtils.showToast(App.getInstance(), "无权限");
                    }
                });
            }
        });
        mDialog.setVisible(false);
        mDialog.setTitle("提示");
        mDialog.setContent("确定拨打电话:" + phone);
    }

    // 获取本地服务
    private List<StoreType> getService(String service) {
        List<StoreType> storeTypeList = new ArrayList<>();
        if (!TextUtils.isEmpty(service)) {
            service = service.substring(1, service.length() - 1);
            String[] arr = service.split(",");
            List<String> list = new ArrayList<>();
            Collections.addAll(list, arr);
            if (list.size() > 0) {
                String[] strName = mContext.getResources().getStringArray(R.array.store_services);
                Integer[] servicesIcon = new Integer[]{
                        R.mipmap.icon_free_wifi_select,
                        R.mipmap.icon_free_toilet_select,
                        R.mipmap.icon_free_hot_water_select,
                        R.mipmap.icon_food_heating_select,
                        R.mipmap.icon_free_air_select,
                        R.mipmap.icon_convenience_charge_select,
                        R.mipmap.icon_convenience_breakfast_select,
                        R.mipmap.icon_express_send_and_receive_select,
                        R.mipmap.icon_bill_payment_select,
                        R.mipmap.icon_fresh_milk_reservation_select,
                        R.mipmap.icon_flowers_reservation_select,
                        R.mipmap.icon_cake_booking_select,
                        R.mipmap.icon_public_welfare_recovery_box_select,
                        R.mipmap.icon_convenient_lock_select,
                        R.mipmap.icon_convenient_moving_select,
                        R.mipmap.icon_rush_pipe_select,
                        R.mipmap.icon_dry_cleaning_collection_select,
                        R.mipmap.icon_home_service_select,
                        R.mipmap.icon_mobile_payment_select,
                        R.mipmap.icon_home_appliance_recycling_select,
                        R.mipmap.icon_dads_toolbox_select,
                        R.mipmap.icon_swing_car_select,
                        R.mipmap.icon_the_annual_illegal_select,
                        R.mipmap.icon_mobile_phone_recycling_select,
                        R.mipmap.icon_broadband_installation_select,
                        R.mipmap.icon_handrecycling,
                        R.mipmap.icon_insuranceagent,
                        R.mipmap.icon_other};
                List<StoreType> serviceBeans = new ArrayList<>();
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        if (!TextUtils.isEmpty(list.get(i).trim())) {
                            int j = Integer.parseInt(list.get(i).trim()) - 1;
                            // 根据集合中的string 数字获取资源文件中的资源
                            StoreType serviceBean = setServiceObject(strName[j], servicesIcon[j]);
                            serviceBeans.add(serviceBean);
                        }
                    }
                }
                storeTypeList.addAll(serviceBeans);
            }
        }
        return storeTypeList;
    }

    // 设置服务项目
    private StoreType setServiceObject(String name, int resId) {
        StoreType service = new StoreType();
        service.setName(name);
        service.setResId(resId);
        return service;
    }

    /**
     * 获取banner图片
     */
    private List<String> getBanner(StoreDetailInfo data) {
        String neighbor_pic_path = data.detail.getNeighbor_pic_path();//门头图
        HashMap<String, String> activityUrlMap = new HashMap<>();//活动和门头图片的Url
        HashMap<String, String> urlMap = data.doc_url;
        List<String> images = new ArrayList<>();
        if (urlMap != null) {
            activityUrlMap.putAll(urlMap);
            TypeToken<List<BannerBean.ListBean>> banner = new TypeToken<List<BannerBean.ListBean>>() {
            };
            List<String> storeList = new ArrayList<>();
            if (!TextUtils.isEmpty(neighbor_pic_path)) {
                storeList.add(neighbor_pic_path);
            }
            String thumbnailPath = data.detail.getStores_thumbnail_path();//街景图
            if (!TextUtils.isEmpty(thumbnailPath)) {
                // 解析街景并加入列表
                try {
                    List<BannerBean.ListBean> listStoreBg =
                            GsonParserUtils.getInstance().fromJson(thumbnailPath, banner);
                    for (int i = 0; i < listStoreBg.size(); i++) {
                        String img = listStoreBg.get(i).getPath_id();
                        if (!TextUtils.isEmpty(img)) {
                            storeList.add(img);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < storeList.size(); i++) {
                String imgUrl = activityUrlMap.get(storeList.get(i));
                images.add(imgUrl);
            }
        }
        return images;
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
